import 'package:flutter/material.dart';
import 'package:lib_uikit/lib_uikit.dart';

import '../theme/gt_colors_v3.dart';
import '../utils/text_utils.dart';
import 'dialog/gt_center_dialog.dart';

/// @Title  虚线文字
/// @Author: bryce
/// @CreateDate: 2023年12月02日01:31:10
class GTDashedLineText extends StatelessWidget {
  final String text;
  final TextStyle textStyle;

  // 文本支持最大多少行(默认10000);
  final int maxLines;

  // 虚线颜色，如果不设置则divider4
  final Color? lineColor;
  final double dashWidth;
  final double dashSpace;
  final double lineHeight;

  // 点击虚线文字弹出弹框中的标题、内容
  final String? dialogTitle;
  final String? dialogContent;

  // 是否展示虚线(默认为true)
  final bool showDashedLine;

  // 是否在点击时候展示弹框(默认为true，
  // 同时也会根据onDashedTextClick判断，若传了则自己不展示弹框由传入方处理点击；
  // 同时也会根据传的dialogTitle和dialogContent判断，若都没值则不展示弹框)
  final bool showDialogWhenClick;

  // 点击虚线文字弹出弹框中的确认按钮（默认不用传，点击关闭弹框）
  // final GestureTapCallback? onDialogConfirmClick;

  // 点击虚线文字的回调（默认不用传，点击弹出弹框；如果传了则不弹出弹框）
  final GestureTapCallback? onDashedTextClick;

  // 弹框中左侧按钮和左侧点击事件
  final String? dialogLeftText;
  final GestureTapCallback? dialogOnLeftTap;

  const GTDashedLineText({
    super.key,
    required this.text,
    required this.textStyle,
    this.maxLines = 10000,
    this.dialogTitle,
    this.dialogContent,
    this.onDashedTextClick,
    this.lineColor,
    this.dashWidth = 4.0,
    this.dashSpace = 3.0,
    this.lineHeight = 1.0,
    this.showDashedLine = true,
    this.showDialogWhenClick = true,
    this.dialogLeftText,
    this.dialogOnLeftTap,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      // 使用父组件的最大宽度
      final maxTextWidth = constraints.maxWidth;

      // 使用方处理点击事件
      if (null != onDashedTextClick) {
        return GestureDetector(
          onTap: onDashedTextClick,
          child: _child(context, maxTextWidth),
        );
      }

      if (showDialogWhenClick && (TextUtils.isNotEmpty(dialogTitle) || TextUtils.isNotEmpty(dialogContent))) {
        return GestureDetector(
          onTap: () => GTCenterDialog.showMessageDialog(context, dialogTitle ?? '', dialogContent ?? '',
              leftText: dialogLeftText, onLeftTap: dialogOnLeftTap),
          child: _child(context, maxTextWidth),
        );
      }

      return _child(context, maxTextWidth);
    });
  }

  _child(BuildContext context, double maxTextWidth) {
    TextStyle realTextStyle =
        textStyle.copyWith(height: textStyle.height ?? 1.4, letterSpacing: textStyle.letterSpacing ?? 0);
    return !showDashedLine
        ? _text(realTextStyle)
        : CustomPaint(
            painter: _DashedLinePainter(
              lineColor: lineColor ?? GTColorsV3.divider4.color,
              dashWidth: dashWidth,
              dashSpace: dashSpace,
              lineHeight: lineHeight,
              textPainter: TextUtils.calculateTextSizeForPainter(context, text,
                  textStyle: realTextStyle, maxLines: maxLines, maxWidth: maxTextWidth),
            ),
            child: _text(realTextStyle),
          );
  }

  _text(TextStyle realTextStyle) {
    return Text(text,
        maxLines: maxLines,
        style: realTextStyle,
        textHeightBehavior: const TextHeightBehavior(applyHeightToLastDescent: false, applyHeightToFirstAscent: false));
  }
}

class _DashedLinePainter extends CustomPainter {
  final Color lineColor;
  final double dashWidth;
  final double dashSpace;
  final double lineHeight;
  final TextPainter textPainter;

  _DashedLinePainter({
    required this.lineColor,
    required this.dashWidth,
    required this.dashSpace,
    required this.lineHeight,
    required this.textPainter,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = lineColor
      ..strokeWidth = lineHeight
      ..style = PaintingStyle.stroke;
    bool isRTL = GTThemeProvider.instance.isRTL();
    double currentX = 0;
    // 通过TextPainter确定每行文本的baseline
    var offset = const Offset(0.0, 0.0);
    for (var line = 0; line < textPainter.computeLineMetrics().length; line++) {
      var metrics = textPainter.computeLineMetrics()[line];
      double y = offset.dy + metrics.height;
      if (isRTL) {
        // 阿语环境
        currentX = size.width;
        double endX = size.width - metrics.width;
        while (currentX > endX) {
          double dashEndX = currentX - dashWidth;
          if (dashEndX < endX) dashEndX = endX;
          canvas.drawLine(
            Offset(currentX, y),
            Offset(dashEndX, y),
            paint,
          );
          currentX -= (dashWidth + dashSpace);
        }
      } else {
        double startX = 0.0;
        while (startX < metrics.width) {
          double dashEndX = startX + dashWidth;
          if (dashEndX > metrics.width) dashEndX = metrics.width;

          canvas.drawLine(
            Offset(startX, y),
            Offset(dashEndX, y),
            paint,
          );

          startX += dashWidth + dashSpace;
        }
      }

      offset = Offset(currentX, offset.dy + metrics.height);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
